package com.example.trailplanner;

import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class NewTrailActivity extends android.support.v4.app.FragmentActivity 
    implements OnMapClickListener, OnMapLongClickListener, NewTrailDialogFragment.NewTrailDialogListener {
	
    private static final int GET_CURRENT_LOCATION = 0;
    private double mCurrentLat = 41.38;
    private double mCurrentLong = 2.17; 
    
    private static final float sDefaultZoom = 15.5f;
    private static final float sDefaultBearing = 0f;
    private static final float sDefaultTilt = 25f;
    private static final String TAG = "NewTrailActivity";
    
    private EditablePolyline mEditablePolyline = null; 

	/**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;
    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.marker_demo);
        setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mEditablePolyline = new EditablePolyline(mMap);
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView
     * MapView}) will show a prompt for the user to install/update the Google Play services APK on
     * their device.
     * <p>
     * A user can return to this Activity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the Activity may not have been
     * completely destroyed during this process (it is likely that it would only be stopped or
     * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
     * {@link #onResume()} to guarantee that it will be called.
     */
    private boolean setUpMapIfNeeded() {
        boolean setup = false;
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
                setup = true;
            }
        }
        return setup;
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        getCurrentLocation();
        // moveMapToMyLocation();
        
        mMap.setOnMapClickListener(this);
        mMap.setOnMapLongClickListener(this);
        
        // Long press to drag.
        mMap.setOnMarkerDragListener( new GoogleMap.OnMarkerDragListener() {
            
            @Override
            public void onMarkerDragStart(Marker marker) {
                int index = EditablePolyline.getIndexForChar(marker.getTitle());
                Log.d("","----- onMarkerDragStart " + index + " letter=" + marker.getTitle() + " id=" + marker.getId() + " -----");
                // MapUtils.bounceMarker(mMap, marker);
                mEditablePolyline.startMovingMarker(index, marker.getPosition() );
            }
            
            @Override
            public void onMarkerDragEnd(Marker marker) {
                Log.d("","----- onMarkerDragEnd " + marker.getTitle() + " id=" + marker.getId() + " -----");
                mEditablePolyline.endMovingMarker();
            }
            
            @Override
            public void onMarkerDrag(Marker marker) {
                int index = EditablePolyline.getIndexForChar(marker.getTitle());
                Log.d("","----- onMarkerDrag " + index + " letter=" + marker.getTitle() + " id=" + marker.getId() + " -----");
                mEditablePolyline.continueMovingMarker(marker.getPosition() );
            }
        });
    }
    
    void replaceMarkerWithLeaf( Marker marker ){
        changeMarkerIcon( marker, R.drawable.leaf );
    }
    
    private void changeMarkerIcon( Marker marker, int resourceId ){
        MarkerOptions newMarker = new MarkerOptions().position(marker.getPosition()).title(marker.getTitle()).draggable(marker.isDraggable()).icon(BitmapDescriptorFactory.fromResource(resourceId));
        marker.remove();
        mMap.addMarker(newMarker.anchor(0.5f, 0f));
    }
    
    private void addMarkerToMap( String markerName, LatLng latLng ){
        MarkerOptions marker = new MarkerOptions().position(latLng).title(markerName).draggable(true);
        mMap.addMarker(marker.anchor(0.5f, 0f));
    }
   
    private void addMarkerAndMoveCamera( String markerName, double lat, double lng ){
        MarkerOptions marker = new MarkerOptions().position(new LatLng(lat, lng)).title(markerName).draggable(true);
        
        // To change icon
        // icon(BitmapDescriptorFactory.fromResource(R.drawable.leaf));
        
        // change anchor
        
        
        mMap.addMarker(marker.anchor(0.5f, 0f)).showInfoWindow();
        
        CameraPosition markerPosition = 
                new CameraPosition.Builder().target(new LatLng(lat, lng))
                .zoom(sDefaultZoom)
                .bearing(sDefaultBearing)
                .tilt(sDefaultTilt)
                .build();
        
        mMap.moveCamera(CameraUpdateFactory.newCameraPosition(markerPosition));
        

    }
    
    
    private void getCurrentLocation(){
        Log.d("","----- getCurrentLocation -----");
    	Intent intent = new Intent(this, LocationActivity.class);
    	// intent.putExtra(LocationActivity.MY_LOCATION, mTravels);
    	startActivityForResult(intent, GET_CURRENT_LOCATION);    	
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	if (requestCode == GET_CURRENT_LOCATION) {
    	     if(resultCode == RESULT_OK){
    	    	 Location location = (Location)data.getParcelableExtra(LocationActivity.MY_LOCATION);
    	    	 mCurrentLat = location.getLatitude();
    	    	 mCurrentLong = location.getLongitude();
    	         Log.d( "","Lat=" + location.getLatitude() );
    	         Log.d( "","Long=" + location.getLongitude() );
    	         Log.d( "","Alt=" + location.getAltitude() );
    	         Log.d( "","Bearing=" + location.getBearing() );
    	         addMarkerAndMoveCamera( "You", mCurrentLat, mCurrentLong );
    	     }
    	     if (resultCode == RESULT_CANCELED) {
    	    	 //Write your code on no result return 
    	     }
    	}
    }
    

    /**
     * When the map is not ready the CameraUpdateFactory cannot be used. This should be called on
     * all entry points that call methods on the Google Maps API.
     */
    private boolean checkReady() {
        if (mMap == null) {
            Toast.makeText(this, R.string.map_not_ready, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_map, menu);
        return true;
    }
    
    /**
     * Under test. Más sencillo pero no tiene todo el asunto de activar la geolocalizacion 
     * si no está disponible.
     */
    private void moveMapToMyLocation() {
        LocationManager locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Criteria crit = new Criteria();
        Location location = locMan.getLastKnownLocation(locMan.getBestProvider(crit, false));
        Log.d( "","Lat=" + location.getLatitude() );
        Log.d( "","Long=" + location.getLongitude() );

        CameraPosition camPos = new CameraPosition.Builder()
        .target(new LatLng(location.getLatitude(), location.getLongitude()))
        .zoom(sDefaultZoom)
        .bearing(sDefaultBearing)
        .tilt(sDefaultTilt)
        .build();

        CameraUpdate camUpdate = CameraUpdateFactory.newCameraPosition(camPos);
        mMap.moveCamera(camUpdate);
    }

    @Override
    public void onMapLongClick(LatLng point) {
    }

    @Override
    public void onMapClick(LatLng latLng) {
        // addMarkerToMap( "otro", latLng );
        mEditablePolyline.addLatLong(latLng);
    }
    
    public void onButton1Clicked( View v ){
        Log.d(TAG,"onButton1Clicked");
        showNewTrailDialog();
        // mPolylineManager.removePoint(3);
    }

    public void onButton2Clicked( View v ){
        Log.d(TAG,"onButton2Clicked");
        // mPolylineManager.reconnectMovedMarker(3);
    }
    
    public void showNewTrailDialog() {
        // Create an instance of the dialog fragment and show it
        DialogFragment dialog = new NewTrailDialogFragment();
        dialog.show(getSupportFragmentManager(), "NewTrailDialogFragment");
    }

    @Override
    public void onDialogPositiveClick(DialogFragment dialog) {
        Log.d(TAG,"onDialogPositiveClick");
    }

    @Override
    public void onDialogNegativeClick(DialogFragment dialog) {
        Log.d(TAG,"onDialogNegativeClick");
    }

}
